package com.usian.user.service.impl;


import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.usian.common.Result;
import com.usian.common.ResultCodeEnum;
import com.usian.entity.*;
import com.usian.user.feign.CarFeignClient;
import com.usian.user.feign.OrderFeignClient;
import com.usian.user.mapper.UsersMapper;
import com.usian.user.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.vo.RentalDetailsVo;
import com.usian.vo.ReserveVo;
import org.apache.poi.hpsf.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-01-15
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public Result<String> getCode(String phone) {
        if (phone == null) {
            return Result.build("手机号不能为空", ResultCodeEnum.USER_PHONE_NULL);
        }
        if (!phone.matches("^1[3-9]\\d{9}$")) {
            return Result.build("手机号格式不正确", ResultCodeEnum.USER_PHONE_ERROR);
        }
        int code = new Random().nextInt(10000);
        if (code < 1000) {
            code += 1000;
        }
        System.out.println(code);
        redisTemplate.opsForValue().set("code_" + phone, code + "", 5, TimeUnit.MINUTES);
        return Result.build(code, ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result<Users> login(String phone, String code) {
        if (phone == null) {
            return Result.build("手机号不能为空", ResultCodeEnum.USER_PHONE_NULL);
        }
        if (!phone.matches("^1[3-9]\\d{9}$")) {
            return Result.build("手机号格式不正确", ResultCodeEnum.USER_PHONE_ERROR);
        }
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Users::getPhoneNumber, phone);
        Users userDB = getOne(wrapper);
        if (userDB == null) {
            //手机号不存在 --- 注册
            userDB = new Users();
            userDB.setNickname("用户" + RandomUtil.randomNumbers(6));
            userDB.setPhoneNumber(phone);
            save(userDB);
            return Result.build(userDB, ResultCodeEnum.SUCCESS);
        } else {
            String codeRedis = redisTemplate.opsForValue().get("code_" + phone);
            if (codeRedis == null) {
                return Result.build("验证码不存在,或者已过期", ResultCodeEnum.VALIDATECODE_ERROR);
            }
            System.out.println("code=============" + code);
            System.out.println("codeRedis=============" + codeRedis);
            if (!code.equals(codeRedis)) {
                return Result.build("验证码不正确", ResultCodeEnum.VALIDATECODE_ERROR);
            }
            return Result.build(userDB, ResultCodeEnum.SUCCESS);
        }
    }

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private CarFeignClient carFeignClient;

    @Override
    public Result<RentalDetailsVo> rentalDetails(Integer userId) {
        Orders order = orderFeignClient.getOrderByUserId(userId).getData();
        System.out.println("order=============" + order);
        if (order == null) {
            return Result.build(null, ResultCodeEnum.ORDERS_NOT_EXISTS);
        }
        Integer orderId = order.getOrderId();
        OrderDetails orderDetails = orderFeignClient.getOrderDetailsByOrderId(orderId).getData();
        if (orderDetails == null) {
            return Result.build(null, ResultCodeEnum.ORDER_DETAILS_NOT_EXIST);
        }
        Integer carId = order.getCarId();
        Cars car = carFeignClient.getCarByCarId(carId).getData();
        if (car == null) {
            return Result.build(null, ResultCodeEnum.CAR_NOT_EXIST);
        }
        String carImageUrl = carFeignClient.getCarImagesByCarId(carId).getData();
        if (carImageUrl == null) {
            return Result.build(null, ResultCodeEnum.DATA_NOT_EXISTS);
        }
        PaymentRecords paymentRecords = orderFeignClient.getPaymentRecordsByOrderId(orderId).getData();
        if (paymentRecords == null) {
            return Result.build(null, ResultCodeEnum.ORDER_DETAILS_NOT_EXIST);
        }

        RentalDetailsVo rentalDetailsVo = new RentalDetailsVo();
        rentalDetailsVo.setImageUrl(carImageUrl);
        rentalDetailsVo.setCarName(car.getCarModel());
        rentalDetailsVo.setUserName(getById(userId).getNickname());
        rentalDetailsVo.setPaymentTime(paymentRecords.getPaymentTime());
        rentalDetailsVo.setRentalStartDate(orderDetails.getRentalStartDate());
        rentalDetailsVo.setRentalEndDate(orderDetails.getRentalEndDate());
        rentalDetailsVo.setPickupLocation(orderDetails.getPickupLocation());
        rentalDetailsVo.setTotalPrice(orderDetails.getTotalCost());
        return Result.build(rentalDetailsVo, ResultCodeEnum.SUCCESS);
    }

    @Override
    public List<ReserveVo> findAllBooked(Integer userId) {
        //根据id查询已经预定的订单
        Orders order = orderFeignClient.findAllBooked(userId).getData();
        if (order == null) {
            return null;
        }
        //根据订单id查询车辆信息
        //获取车辆id
        Integer carId = order.getCarId();
        Cars cars = carFeignClient.getCarByCarId(carId).getData();
        String carImageUrl = carFeignClient.getCarImagesByCarId(carId).getData();
        //封装vo
        ReserveVo reserveVo = new ReserveVo();
        reserveVo.setCarId(carId);
        reserveVo.setImageUrl(Collections.singletonList(carImageUrl));
        reserveVo.setCarModel(cars.getCarModel());
        reserveVo.setFuelLevel(cars.getFuelLevel());
        reserveVo.setPricePerHour(cars.getPricePerHour());
        reserveVo.setOrderStatus(order.getOrderStatus());

        ArrayList<ReserveVo> reserveVos = new ArrayList<>();
        reserveVos.add(reserveVo);
        return reserveVos;
    }

    @Override
    public List<ReserveVo> findAllHistory(Integer userId) {
        //根据当前用户id查询历史订单
        List<Orders> ordersList = orderFeignClient.findOrderHistory(userId).getData();
        if (ordersList == null) {
            return null;
        }
        //根据订单id查询车辆信息
        List<ReserveVo> reserveVoList = new ArrayList<>();
        for (Orders orders : ordersList) {
            //获取车辆id
            Integer carId = orders.getCarId();
            Cars cars = carFeignClient.getCarByCarId(carId).getData();
            String carImageUrl = carFeignClient.getCarImagesByCarId(carId).getData();
            //封装vo
            ReserveVo reserveVo = new ReserveVo();
            reserveVo.setCarId(carId);
            reserveVo.setImageUrl(Collections.singletonList(carImageUrl));
            reserveVo.setCarModel(cars.getCarModel());
            reserveVo.setFuelLevel(cars.getFuelLevel());
            reserveVo.setPricePerHour(cars.getPricePerHour());
            reserveVo.setOrderStatus(orders.getOrderStatus());
            reserveVoList.add(reserveVo);
        }

        return reserveVoList;
    }

    @Override
    public List<ReserveVo> findAllList(Integer userId) {
        //根据当前用户id查询所有订单
        List<Orders> ordersList = orderFeignClient.findAllList(userId).getData();
        if (ordersList == null) {
            return null;
        }
        //根据订单id查询车辆信息
        List<ReserveVo> reserveVoList = new ArrayList<>();
        for (Orders orders : ordersList) {
            //获取车辆id
            Integer carId = orders.getCarId();
            Cars cars = carFeignClient.getCarByCarId(carId).getData();
            String carImageUrl = carFeignClient.getCarImagesByCarId(carId).getData();
            //封装vo
            ReserveVo reserveVo = new ReserveVo();
            reserveVo.setOrderId(orders.getOrderId());
            reserveVo.setCarId(carId);
            reserveVo.setImageUrl(Collections.singletonList(carImageUrl));
            reserveVo.setCarModel(cars.getCarModel());
            reserveVo.setFuelLevel(cars.getFuelLevel());
            reserveVo.setPricePerHour(cars.getPricePerHour());
            reserveVo.setOrderStatus(orders.getOrderStatus());
            reserveVoList.add(reserveVo);
        }

        return reserveVoList;
    }
    @Override
    public ReserveVo findReservedCar(Integer userId, Integer carId) {
        if (userId == null || carId == null) {
            return null;
        }
        //根据用户id查询用户信息
        Users users = getById(userId);
        //根据用户id查询预定的订单
        Orders order = orderFeignClient.findAllBooked(userId).getData();
        System.out.println("order预定中-----------------------------------"+order);
        ReserveVo reserveVo = new ReserveVo();
        if (order != null) {
            //根据订单id查询车辆信息
            Cars cars = carFeignClient.getCarByCarId(carId).getData();
            //封装vo
            reserveVo.setCarId(carId);
            reserveVo.setUserName(users.getNickname());
            reserveVo.setCarModel(cars.getCarModel());
            reserveVo.setCreatedAt(LocalDate.from(order.getCreatedAt()));
            reserveVo.setStartTime(LocalDate.from(order.getStartTime()));
            reserveVo.setEndTime(LocalDate.from(order.getEndTime()));
            reserveVo.setLocationPoint(cars.getLocationPoint());
            //总花费
            long hours = ChronoUnit.HOURS.between(order.getStartTime(), order.getEndTime());
            // 获取车辆的价格
            BigDecimal price = cars.getPricePerHour();
            // 计算总花费
            BigDecimal totalPrice = price.multiply(BigDecimal.valueOf(hours));
            reserveVo.setTotalPrice(totalPrice);
        }
        System.out.println("res-------------"+reserveVo);
        return reserveVo;
    }

    @Override
    public List<ReserveVo> findAllzhifu(Integer userId) {
        //根据id查询已经预定的订单
        Orders order = orderFeignClient.findAllzhifu(userId).getData();
        if (order == null) {
            return null;
        }
        //根据订单id查询车辆信息
        //获取车辆id
        Integer carId = order.getCarId();
        Cars cars = carFeignClient.getCarByCarId(carId).getData();
        String carImageUrl = carFeignClient.getCarImagesByCarId(carId).getData();
        //封装vo
        ReserveVo reserveVo = new ReserveVo();
        reserveVo.setCarId(carId);
        reserveVo.setImageUrl(Collections.singletonList(carImageUrl));
        reserveVo.setCarModel(cars.getCarModel());
        reserveVo.setFuelLevel(cars.getFuelLevel());
        reserveVo.setPricePerHour(cars.getPricePerHour());
        reserveVo.setOrderStatus(order.getOrderStatus());

        ArrayList<ReserveVo> reserveVos = new ArrayList<>();
        reserveVos.add(reserveVo);
        return reserveVos;
    }

    @Override
    public ReserveVo findzhifuCar(Integer userId, Integer carId) {
        if (userId == null || carId == null) {
            return null;
        }
        //根据用户id查询用户信息
        Users users = getById(userId);
        //根据用户id查询支付的订单
        Orders order = orderFeignClient.findAllzhifu(userId).getData();
        System.out.println("order支付-----------------------------------"+order);
        ReserveVo reserveVo = new ReserveVo();
        if (order != null) {
            //根据订单id查询车辆信息
            Cars cars = carFeignClient.getCarByCarId(carId).getData();
            //封装vo
            reserveVo.setCarId(carId);
            reserveVo.setUserName(users.getNickname());
            reserveVo.setCarModel(cars.getCarModel());
            reserveVo.setCreatedAt(LocalDate.from(order.getCreatedAt()));
            reserveVo.setStartTime(LocalDate.from(order.getStartTime()));
            reserveVo.setEndTime(LocalDate.from(order.getEndTime()));
            reserveVo.setLocationPoint(cars.getLocationPoint());
            //总花费
            long hours = ChronoUnit.HOURS.between(order.getStartTime(), order.getEndTime());
            // 获取车辆的价格
            BigDecimal price = cars.getPricePerHour();
            // 计算总花费
            BigDecimal totalPrice = price.multiply(BigDecimal.valueOf(hours));
            reserveVo.setTotalPrice(totalPrice);
        }
        System.out.println("res-------------"+reserveVo);
        return reserveVo;
    }


}
